package cn.shoptnt.service.trade.order.command.impl;

import cn.shoptnt.client.member.MemberClient;
import cn.shoptnt.framework.context.ApplicationContextHolder;
import cn.shoptnt.framework.util.DateUtil;
import cn.shoptnt.model.member.dos.MemberPointHistory;
import cn.shoptnt.model.trade.order.dto.OrderDTO;
import cn.shoptnt.model.trade.order.vo.CommandResult;
import cn.shoptnt.service.trade.order.command.OrderCreateCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单信息入库命令执行器
 *
 * @author zs
 * @version v2.0
 * @since v2.0
 * 2022-01-17
 */
@Service
public class MemberPointDeductCommand implements OrderCreateCommand {
    @Autowired
    private MemberClient memberClient;


    public CommandResult execute(OrderDTO orderDTO) {
        CommandResult result = new CommandResult(true, "成功");

        result.setRollback(this, orderDTO);
        //订单入库，扣减使用积分
        Long consumerPoint = orderDTO.getPrice().getExchangePoint();
        if (consumerPoint <= 0) {
           return  result;
        }
        try {
            MemberPointHistory history = new MemberPointHistory();
            history.setConsumPoint(consumerPoint);
            history.setConsumPointType(0);
            history.setGradePointType(0);
            history.setGradePoint(0);
            history.setMemberId(orderDTO.getMemberId());
            history.setTime(DateUtil.getDateline());
            history.setReason("创建订单，消费积分");
            history.setOperator(orderDTO.getMemberName());

            this.memberClient.pointOperation(history);
        } catch (Exception e) {
            return new CommandResult(false, "积分扣减失败");
        }
        return result;

    }

    //数据库操作不需要在这里回滚，使用的spring 或 seata事务自动回滚了
    //积分业务没有需要手动回滚的
    public void rollback(OrderDTO order) {

    }

}
